// This is the main DLL file.

#include "stdafx.h"
#include "AsfReader.h"
#include "Tools.h"
#include "checkhr.h"
#include <vector>

using namespace WMFInterface;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Generic;
using namespace std;

namespace WMFWrapper
{
	AsfReader::AsfReader(String^ fileName)
	{
		reader_ = nullptr;
		IWMSyncReader* ptr;
		CHECK_HR(::WMCreateSyncReader(NULL, 0, &ptr));
		reader_ = ptr;
		pin_ptr<const wchar_t> fname = PtrToStringChars(fileName);
		HRESULT hr = reader_->Open(fname);
		if (FAILED(hr))
		{
			reader_->Release();
			reader_ = nullptr;
			Marshal::ThrowExceptionForHR(hr);
		}
	}

	AsfReader::~AsfReader()
	{
		if (reader_ != nullptr)
		{
			reader_->Close();
			reader_->Release();
			reader_ = nullptr;
		}
	}

	Profile^ AsfReader::GetProfile()
	{
		CComPtr<IWMProfile2> profItf;
		CHECK_HR(reader_->QueryInterface(IID_IWMProfile2, reinterpret_cast<void**>(&profItf)));
		DWORD streamsCount;
		CHECK_HR(profItf->GetStreamCount(&streamsCount));
		List<Stream^>^ streams = gcnew List<Stream^>;
		WORD scripts;
		for (WORD s = 1; s <= streamsCount; ++s)
		{
			CComPtr<IWMStreamConfig> tmpItf;
			CHECK_HR(profItf->GetStreamByNumber(s, &tmpItf));
			CComPtr<IWMStreamConfig3> strItf;
			CHECK_HR(tmpItf->QueryInterface(IID_IWMStreamConfig3, reinterpret_cast<void**>(&strItf)));
			Stream^ stream = gcnew Stream((int)s);
			WORD len;
			CHECK_HR(strItf->GetLanguage(NULL, &len));
			vector<WCHAR> buf(len);
			CHECK_HR(strItf->GetLanguage(&buf[0], &len));
			stream->Language = gcnew String(&buf[0]);
			DWORD bitRate;
			CHECK_HR(strItf->GetBitrate(&bitRate));
			stream->BitRate = bitRate;
			GUID id;
			CHECK_HR(strItf->GetStreamType(&id));
			stream->Type = Tools::StreamTypeFromGuid(id);
			streams->Add(stream);
			CComPtr<IWMHeaderInfo> header;
			CHECK_HR(reader_->QueryInterface(IID_IWMHeaderInfo, reinterpret_cast<void**>(&header)));
			CHECK_HR(header->GetScriptCount(&scripts));
		}
		Profile^ pf = gcnew Profile(streams);
		pf->ScriptsCount = scripts;
		return pf;
	}
}